using System;
using System.Collections.Generic;
using QFramework;
using UnityEngine;
using Random = System.Random;

namespace ProjectSurvivor
{
	
	public partial class EnemyGenerator : ViewController
	{
		[SerializeField] 
		public LevelConfig Config;
		
		private float mCurrentGenerateSeconds = 0;
		private float mCurrentWaveSeconds = 0;
		
		public static BindableProperty<int> EnemyCount=new BindableProperty<int>(0);
		

		private Queue<EnemyWave> mEnemyWavesQueue = new Queue<EnemyWave>();

		public int WaveCount = 0;

		private int mTotalCount = 0;
		public bool LastWave => WaveCount == mTotalCount;
		public EnemyWave CurrentWave=> mCurrentWave;
		private void Start()
		{
			foreach (var group in Config.EnemyWaveGroups)
			{
				foreach (var wave in group.Waves)
				{
					mEnemyWavesQueue.Enqueue(wave);
					mTotalCount++;
				}
			}
		}
		
		private EnemyWave mCurrentWave=null;

		private void Update()
		{
			if (mCurrentWave == null)
			{
				if (mEnemyWavesQueue.Count > 0)
				{
					WaveCount++;
					mCurrentWave = mEnemyWavesQueue.Dequeue();
					mCurrentGenerateSeconds = 0;
					mCurrentWaveSeconds = 0;
				}
			}

			if (mCurrentWave != null)
			{
				mCurrentGenerateSeconds += Time.deltaTime;
				mCurrentWaveSeconds += Time.deltaTime;
				
				if (mCurrentGenerateSeconds >= mCurrentWave.GenerateDuration)
				{
					mCurrentGenerateSeconds = 0;
					var player = Player.Default;
					if (player != null)
					{
						var xOry = RandomUtility.Choose(-1, 1);
						var pos = Vector2.zero;
						if (xOry == -1)
						{
							pos.x=RandomUtility.Choose(CameraController.LBTrans.position.x, 
								CameraController.RTTrans.position.x);
							pos.y=UnityEngine.Random.Range(CameraController.LBTrans.position.y,
								CameraController.RTTrans.position.y);
						}
						else
						{
							pos.y=RandomUtility.Choose(CameraController.LBTrans.position.y, 
								CameraController.RTTrans.position.y);
							pos.x=UnityEngine.Random.Range(CameraController.LBTrans.position.x,
								CameraController.RTTrans.position.x);
						}
						
						//围绕主角位置附近生成怪物
						//var randomAngle=UnityEngine.Random.Range(0,360f);
						//var randomRadius = randomAngle * Mathf.Deg2Rad;
						//var direction=new Vector3(Mathf.Cos(randomRadius), Mathf.Sin(randomRadius));
						//var generatePos = player.transform.position + direction * 10;
				
						mCurrentWave.EnemyPrefab.Instantiate()
							.Position(pos)
							.Self(self =>
							{
								var enemy = self.GetComponent<IEnemy>();
								enemy.SetSpeedScale(mCurrentWave.SpeedScale);
								enemy.SetHPScale(mCurrentWave.HpScale);
							})
							.Show();
					}
				}

				if (mCurrentWaveSeconds >= mCurrentWave.Seconds)
				{
					mCurrentWave=null;
				}
			}
		}
	}
}